<template>
  <el-dialog
    v-model="visible"
    :title="isLogin ? '登录' : '注册'"
    width="400px"
    :before-close="handleClose"
    class="login-modal"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="login-form"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入用户名"
          :prefix-icon="User"
          clearable
        />
      </el-form-item>
      
      <el-form-item v-if="!isLogin" label="昵称" prop="nickname">
        <el-input
          v-model="form.nickname"
          placeholder="请输入昵称"
          :prefix-icon="User"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          :prefix-icon="Lock"
          show-password
          clearable
        />
      </el-form-item>
      
      <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          :prefix-icon="Lock"
          show-password
          clearable
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isLogin ? '登录' : '注册' }}
        </el-button>
      </div>
      <div class="switch-mode">
        <span>{{ isLogin ? '还没有账号？' : '已有账号？' }}</span>
        <el-button type="text" @click="switchMode">
          {{ isLogin ? '立即注册' : '立即登录' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { login, register } from '../api/userApi'
import { getUserInfo } from '../api/serverApi'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)
const isLogin = ref(true)
const visible = ref(false)

const form = reactive({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== form.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

watch(() => props.modelValue, (val) => {
  visible.value = val
})

watch(visible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    resetForm()
  }
})

const resetForm = () => {
  form.username = ''
  form.nickname = ''
  form.password = ''
  form.confirmPassword = ''
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const switchMode = () => {
  isLogin.value = !isLogin.value
  resetForm()
}

const handleClose = () => {
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const data = {
      username: form.username,
      password: form.password
    }
    
    // 注册时添加昵称字段
    if (!isLogin.value) {
      data.nickname = form.nickname
    }
    
    const response = isLogin.value ? await login(data) : await register(data)
    
    if (response.data.code === 200) {
      if (isLogin.value) {
      const token = response.data.data.token
      console.log('[LoginModal] 获取到token:', token)
      
      // 登录成功 - 先保存token
      userStore.setToken(token)
      console.log('[LoginModal] token已保存到localStorage:', localStorage.getItem('access-key'))
      
      // 然后获取完整的用户信息
      try {
        console.log('[LoginModal] 开始调用getUserInfo接口...')
        console.log('[LoginModal] 请求URL将是:', 'http://localhost:8980/js/api/auth/userinfo')
        console.log('[LoginModal] 请求头access-key:', localStorage.getItem('access-key'))
        
        const userInfoResponse = await getUserInfo()
        console.log('[LoginModal] getUserInfo响应:', userInfoResponse)
        
        if (userInfoResponse.success) {
          // 保存完整的用户信息（包含role字段）
          userStore.setUserInfo(userInfoResponse.data)
          console.log('[LoginModal] 用户信息已保存:', userInfoResponse.data)
          ElMessage.success('登录成功！')
          visible.value = false
        } else {
          console.error('[LoginModal] getUserInfo返回失败:', userInfoResponse)
          ElMessage.error('获取用户信息失败')
        }
      } catch (userInfoError) {
        console.error('[LoginModal] getUserInfo调用异常:', userInfoError)
        console.error('[LoginModal] 错误详情:', {
          message: userInfoError.message,
          response: userInfoError.response,
          request: userInfoError.request,
          config: userInfoError.config
        })
        ElMessage.error('获取用户信息失败，请重新登录')
        userStore.logout()
      }
      } else {
        // 注册成功
        ElMessage.success('注册成功！请登录')
        isLogin.value = true
        resetForm()
        return
      }
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-modal :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.login-modal :deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f0f0f0;
}

.login-modal :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.login-form {
  padding: 20px 0;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-input {
  height: 44px;
}

.login-form .el-input__inner {
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.login-form .el-input__inner:focus {
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 16px;
}

.dialog-footer .el-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

.dialog-footer .el-button--primary {
  background: #4CAF50;
  border-color: #4CAF50;
}

.dialog-footer .el-button--primary:hover {
  background: #45a049;
  border-color: #45a049;
}

.switch-mode {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  color: #6b7280;
  font-size: 14px;
}

.switch-mode .el-button--text {
  color: #4CAF50;
  font-weight: 500;
  padding: 0 4px;
}

.switch-mode .el-button--text:hover {
  color: #45a049;
}
</style>